package com.mingchuang.etc2.serial;

import android.util.Log;

import com.embedsky.serialport.SerialPort;
import com.mingchuang.etc2.listener.SerialListener;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * - Description:串口控制
 * - Author: XinJie.Li
 * - CreateDate:2025/7/15 15:24
 */
public class SerialCtrl {
    private ExecutorService mThreadPoolExecutor = Executors.newCachedThreadPool();
    private SerialPort mSerialPort;
    private InputStream mInputStream;
    private OutputStream mOutputStream;
    private SerialListener mListener;
    private boolean isOpened = false;
    private String mPath;

    public SerialCtrl(SerialListener listener) {
        this.mListener = listener;
    }

    /**
     * 打开串口
     *
     * @param serialPath 串口地址
     * @param baudRate   波特率
     */
    public void openSerialPort(String serialPath, int baudRate) {
        try {
            mPath = serialPath;
            mSerialPort = new SerialPort(new File(mPath), baudRate);
            mInputStream = mSerialPort.getInputStream();
            mOutputStream = mSerialPort.getOutputStream();
            isOpened = true;
            if (mListener != null) {
                mListener.onSerialOpenSuccess(mPath);
            }
            mThreadPoolExecutor.execute(new ReceiveDataThread());
        } catch (Exception e) {
            if (mListener != null) {
                mListener.onSerialOpenException(mPath, e);
            }
        }
    }

    /**
     * 关闭串口
     */
    public void close() {
        try {
            if (mInputStream != null) {
                mInputStream.close();
            }
            if (mOutputStream != null) {
                mOutputStream.close();
            }
            isOpened = false;
            mListener.onSerialCloseSuccess(mPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送串口数据
     *
     * @param bytes 发送数据
     */
    public void sendSerialData(byte[] bytes) {
        if (!isOpened) {
            return;
        }
        try {
            if (mOutputStream != null) {
                mOutputStream.write(bytes);
                mOutputStream.flush();
                if (mListener != null) {
                    mListener.onSendData(bytes);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回串口是否开启
     *
     * @return 是否开启
     */
    public boolean isOpened() {
        return isOpened;
    }

    /**
     * 串口返回数据内容读取
     */
    private class ReceiveDataThread extends Thread {
        @Override
        public void run() {
            super.run();
            try {
                while (isOpened) {
                    if (mInputStream != null) {
                        if (mInputStream.available() <= 0) {
                            continue;
                        } else {
                            sleep(100);
                        }
                        byte[] tempData = new byte[2048];
                        int size = mInputStream.read(tempData);
                        byte[] readData = new byte[size];
                        System.arraycopy(tempData, 0, readData, 0, size);
                        if (mListener != null) {
                        if (size > 0) {
                                mListener.onReceiveData(readData);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("LogMessage", "run: " + e.getMessage());
            }
        }
    }
}